<?php

namespace App\Http\Controllers;

use App\Http\Requests\StoreMenuRequest;
use App\Http\Requests\UpdateMenuRequest;
use App\Http\Resources\MenuResource;
use App\Http\Traits\CheckPermission;
use App\Models\Menu;
use App\Models\Permission;
use App\Services\MenuService;
use Illuminate\Http\Request;

class MenuController extends Controller
{
    use CheckPermission;

    protected $menuService;
    protected $resource = 'menus';

    public function __construct(MenuService $menuService)
    {
        $this->menuService = $menuService;
        $this->middleware('auth.api');
    }

    public function index(Request $request)
    {
        // 检查查看权限
        $this->authorizeButtonPermission($this->resource, Permission::ACTION_VIEW);

        if ($request->has('tree')) {
            $conditions = [];
            if ($request->has('status')) {
                $conditions['status'] = $request->status;
            }
            
            // 如果是用于权限分配，排除按钮类型的菜单
            $excludeButtons = $request->boolean('exclude_buttons', false);
            if ($excludeButtons) {
                $conditions['type'] = [Menu::TYPE_DIRECTORY, Menu::TYPE_MENU];
            }
            
            $menus = Menu::tree(0, $conditions);
            // 使用Resource格式化树形数据，包括时间字段
            // tree方法返回的是Collection，且已设置children关系，Resource会自动处理
            $formattedMenus = MenuResource::collection($menus)->resolve(request());
            return $this->success($formattedMenus, '获取成功');
        }

        $query = Menu::with('parent');

        // 添加搜索条件
        if ($request->has('title')) {
            $query->where('title', 'like', '%' . $request->title . '%');
        }
        if ($request->has('type')) {
            $query->where('type', $request->type);
        }
        if ($request->has('status')) {
            $query->where('status', $request->status);
        }

        $menus = $query->orderBy('sort')
            ->orderBy('id')
            ->get();

        return $this->success(MenuResource::collection($menus), '获取成功');
    }

    public function store(StoreMenuRequest $request)
    {
        // 检查新增权限
        $this->authorizeButtonPermission($this->resource, Permission::ACTION_CREATE);

        $menu = $this->menuService->create($request->validated());
        return $this->success(new MenuResource($menu), '创建成功');
    }

    public function show($id)
    {
        // 检查查看权限
        $this->authorizeButtonPermission($this->resource, Permission::ACTION_VIEW);

        $menu = Menu::with('parent')->findOrFail($id);
        return $this->success(new MenuResource($menu), '获取成功');
    }

    public function update(UpdateMenuRequest $request, $id)
    {
        // 检查编辑权限
        $this->authorizeButtonPermission($this->resource, Permission::ACTION_UPDATE);

        $menu = Menu::findOrFail($id);
        $menu = $this->menuService->update($menu, $request->validated());
        return $this->success(new MenuResource($menu), '更新成功');
    }

    public function destroy($id)
    {
        // 检查删除权限
        $this->authorizeButtonPermission($this->resource, Permission::ACTION_DELETE);

        $menu = Menu::findOrFail($id);
        
        try {
            $this->menuService->delete($menu);
            return $this->success(null, '删除成功');
        } catch (\Exception $e) {
            return $this->error($e->getMessage(), 400);
        }
    }

    public function routes()
    {
        $user = auth()->user();
        $routes = $this->menuService->getUserRoutes($user);
        return $this->success($routes, '获取成功');
    }
}

